# build-pkg BOARD_NAME [OPTIONS] PKG_NAME
PROJROOT=$PWD/../

BOARD=
BIN=`basename $0`

function usage()
{
	echo "Usage:"
	echo "build_pkg.sh BOARD_NAME [OPTIONS] PKG_NAME"
}

# sanity checks
###############
# check that we are inside the chroot
if [ ! -e ${PROJROOT}/../embtoo ]; then
	PROJROOT=/opt/embtoo
else
	echo "You cannot run this command outside the chroot environment"
	exit
fi
# simple mode
if [ $BIN == "build_pkg.sh" ]; then
	BOARD=$1
	shift 1
# board name
else
	BOARD=`echo $BIN | cut -d "_" -f 2`
fi

if [ -z $BOARD ]; then
	usage
	exit
fi

BOARDDIR=${PROJROOT}/boards/${BOARD}

if [ ! -e ${BOARDDIR} ]; then
	echo "Board ${BOARD} does not exist"
	exit
fi

if [ ! -e ${BOARDDIR}/config ]; then
	echo "Board ${BOARD} does not have a valid config file"
	exit
fi


# setup the build environment
#############################
# read the default configuration
source ${BOARDDIR}/config
# board sanity checks
if [ -z $ARCH ]; then
	echo "Bad formed config file. ARCH is not set"
	exit
fi

if [ -z $CHOST ]; then
	echo "Bad formed config file. CHOST is not set"
	exit
fi

if [ -z $PROFILE ]; then
	echo "Bad formed config file. PROFILE is not set"
	exit
fi

# check that crossdev is already installed and configured for this board
which ${CHOST}-gcc
if [ $? -eq 1 ]; then
	echo "Not suitable gcc, trying to install it"
	which crossdev
	if [ $? -eq 1 ]; then
		emerge -av portage-utils crossdev
	fi
	crossdev -t ${CHOST}
fi
# setup some environment variables
PORTAGE_CONFIGROOT=${BOARDDIR}/sys
ROOT=${BOARDDIR}/build
CBUILD=$(portageq envvar CHOST)
CONFIG_SITE=${PORTAGE_CONFIGROOT}/etc/config.site
# this fixes some packages and fucks up some others
# CFLAGS="-I${ROOT}/usr/include"
# LDFLAGS="-L${ROOT}/usr/lib"

if [ ! -e $PORTAGE_CONFIGROOT} ]; then
	mkdir -p ${PORTAGE_CONFIGROOT}/etc
fi

if [ -e ${PORTAGE_CONFIGROOT}/etc/make.profile ]; then
	rm ${PORTAGE_CONFIGROOT}/etc/make.profile
fi
ln -sn /usr/portage/profiles/${PROFILE} "${PORTAGE_CONFIGROOT}/etc/make.profile"


if [ ! -e ${ROOT} ]; then
	mkdir -p ${ROOT}
fi

# TODO dump variables into sysconfig make.conf
echo "CHOST=\"${CHOST}\"" > ${PORTAGE_CONFIGROOT}/etc/make.conf
echo "ARCH=\"${ARCH}\"" >> ${PORTAGE_CONFIGROOT}/etc/make.conf
echo "PORTDIR_OVERLAY=\"/opt/embtoo/overlay\"" >> ${PORTAGE_CONFIGROOT}/etc/make.conf
echo "CONFIG_SITE=\"${CONFIG_SITE}\"" >> ${PORTAGE_CONFIGROOT}/etc/config.site
# config.site default values
# http://bugs.gentoo.org/224685
echo "source /usr/share/config.site" > ${PORTAGE_CONFIGROOT}/etc/config.site
echo "gl_cv_func_wcwidth_works=yes" >> ${PORTAGE_CONFIGROOT}/etc/config.site
# masked packages

export PORTAGE_CONFIGROOT ROOT CBUILD CONFIG_SITE #CFLAGS LDFLAGS

emerge $*
